package cn.icanci.loopstack.rec.sample.sdk.http.facade;

import cn.hutool.json.JSONUtil;
import cn.icanci.loopstack.rec.common.aggregation.model.DomainDTO;
import cn.icanci.loopstack.rec.engine.sdk.actuator.RecRuleEngineActuator;
import cn.icanci.loopstack.rec.engine.sdk.actuator.RuleEngineRequest;
import cn.icanci.loopstack.rec.engine.sdk.actuator.RuleEngineResponse;
import cn.icanci.loopstack.rec.engine.sdk.spi.DomainSPI;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/12 22:45
 */
@RestController
@RequestMapping("/rec/sample")
public class RuleExecutorFacade implements InitializingBean {

    private static final Logger   logger = LoggerFactory.getLogger(RuleExecutorFacade.class);

    @Resource
    private DomainSPI             domainSPI;

    @Resource
    private RecRuleEngineActuator actuator;

    /**
     * http://localhost:9090/rec/sample/testSpi
     * 
     * @return testSpi
     */
    @GetMapping("testSpi")
    public DomainDTO testSpi() {
        return domainSPI.loadOne("TestA");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Thread thread = new Thread(() -> {
            while (true) {
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(10));
                RuleEngineRequest request = new RuleEngineRequest();
                request.setParameters(Maps.newHashMap());
                request.setDomainCode("TestA");
                request.setSceneCode("T3");

                RuleEngineResponse response = actuator.executor(request);
                logger.warn("[RuleExecutorFacade][run] response message:{}", JSONUtil.toJsonStr(response));
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
}
